package com.softeem.ossmusic.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.ossmusic.comm.R;
import com.softeem.ossmusic.entity.Admin;
import com.softeem.ossmusic.service.AdminService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员管理模块
 */
@Tag(name="管理员管理模块")
@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Operation(summary = "管理员列表",description = "分页查询管理员列表")
    @Parameters({
            @Parameter(name = "page",description = "页码"),
            @Parameter(name = "limit",description = "数据条数")
    })
    @GetMapping("/admin/list")
    public R list(@RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "5")Integer limit){
        IPage<Admin> ipage = new Page<>(page, limit);
        adminService.page(ipage);
        return R.success().setData(ipage.getRecords()).setCount(ipage.getTotal());
    }

    @Operation(summary = "管理员添加",description = "添加管理员")
    @PostMapping("/admin/add")
    public R add(@RequestBody Admin admin){
       return adminService.add(admin);
    }
    
    @Operation(summary = "管理员修改",description = "根据id修改管理员")
    @PutMapping("/admin/update")
    public R update(@RequestBody Admin admin){
        if(admin.getId() == null || !adminService.existsById(admin.getId())){
            return R.error().setMsg("管理员不存在");
        }
        if(adminService.updateById(admin)){
            return R.success().setMsg("修改成功");
        }
        return R.error().setMsg("修改失败");
    }

    @Operation(summary = "管理员删除",description = "根据id删除管理员")
    @Parameters({
            @Parameter(name = "id",description = "管理员id")
    })
    @DeleteMapping("/admin/delete")
    public R delete(Integer id){
        if(id == null || !adminService.existsById(id)){
            return R.error().setMsg("管理员不存在");
        }
        if(adminService.removeById(id)){
            return R.success().setMsg("删除成功");
        }
        return R.error().setMsg("删除失败");
    }

    @Operation(summary = "管理员登录",description = "根据用户名和密码登录")
    @Parameters({
            @Parameter(name = "username",description = "用户名"),
            @Parameter(name = "password",description = "密码")
    })
    @GetMapping("/admin/login")
    public R login(String username, String password, HttpSession session){
        R result = adminService.login(username,password);
        // 登录成功则将用户信息存入session
        if(result.getCode() == 0 && result.getData() != null){
            Admin admin = (Admin) result.getData();
            // 存储登录时间
            session.setAttribute("loginTime", new Date());
            // 存储用户信息
            session.setAttribute("currentAdmin", admin);
        }
        return result;
    }
    
    @Operation(summary = "获取当前登录管理员信息",description = "获取当前登录的管理员信息")
    @GetMapping("/admin/getInfo")
    public R getInfo(HttpSession session){
        Admin admin = (Admin) session.getAttribute("currentAdmin");
        if(admin == null){
            return R.error().setMsg("未登录");
        }
        // 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("username", admin.getUsername());
        data.put("account", admin.getUsername()); // 使用username作为账号
        data.put("createTime", admin.getCreateTime());
        data.put("role", "管理员");
        data.put("loginTime", session.getAttribute("loginTime"));
        
        return R.success().setData(data);
    }
    
    @Operation(summary = "管理员退出登录",description = "清除当前登录用户的session信息")
    @PostMapping("/admin/logout")
    public R logout(HttpSession session){
        // 清除session中的用户信息
        session.removeAttribute("currentAdmin");
        session.removeAttribute("loginTime");
        // 也可以选择使整个session失效
        // session.invalidate();
        return R.success().setMsg("退出成功");
    }
    
    @Operation(summary = "管理员详情", description = "根据id查询管理员详情")
    @GetMapping("/admin/details")
    public R details(Integer id){
        Admin admin = adminService.getById(id);
        if(admin == null){
            return R.error().setMsg("管理员不存在");
        }
        //隐藏密码
        admin.setPassword(null);
        return R.success().setData(admin);
    }
    
    // 内部静态类用于接收密码修改请求
    private static class PasswordUpdateRequest {
        private Integer id;
        private String oldPassword;
        private String password;
        
        // Getters and Setters
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getOldPassword() {
            return oldPassword;
        }
        public void setOldPassword(String oldPassword) {
            this.oldPassword = oldPassword;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
    }
    
    @Operation(summary = "修改管理员密码", description = "修改管理员密码")
    @PostMapping("/admin/updatePassword")
    public R updatePassword(@RequestBody PasswordUpdateRequest request){
        if(request.getId() == null || !adminService.existsById(request.getId())){
            return R.error().setMsg("管理员不存在");
        }
        if(request.getOldPassword() == null || request.getOldPassword().trim().isEmpty()){
            return R.error().setMsg("旧密码不能为空");
        }
        if(request.getPassword() == null || request.getPassword().trim().isEmpty()){
            return R.error().setMsg("新密码不能为空");
        }
        
        // 获取原管理员信息
        Admin oldAdmin = adminService.getById(request.getId());
        
        // 验证旧密码是否正确
        if(!oldAdmin.getPassword().equals(request.getOldPassword())){
            return R.error().setMsg("旧密码错误");
        }
        
        // 验证新密码是否与旧密码相同
        if(request.getOldPassword().equals(request.getPassword())){
            return R.error().setMsg("新密码不能与旧密码相同");
        }
        
        // 构建更新对象
        Admin updateAdmin = new Admin();
        updateAdmin.setId(request.getId());
        updateAdmin.setPassword(request.getPassword());
        
        if(adminService.updateById(updateAdmin)){
            return R.success().setMsg("密码修改成功");
        }
        return R.error().setMsg("密码修改失败");
    }
    
    @Operation(summary = "启用/禁用管理员", description = "根据id启用或禁用管理员")
    @PutMapping("/admin/setStatus")
    public R setStatus(Integer id, Integer status){
        if(id == null || !adminService.existsById(id)){
            return R.error().setMsg("管理员不存在");
        }
        if(status == null || (status != 0 && status != 1)){
            return R.error().setMsg("状态值无效，必须为0(禁用)或1(启用)");
        }
        
        Admin admin = new Admin();
        admin.setId(id);
        admin.setStatus(status);
        
        if(adminService.updateById(admin)){
            return R.success().setMsg("状态更新成功");
        }
        return R.error().setMsg("状态更新失败");
    }

}
